﻿using System;
using System.Linq;
using Enyim.Caching;
using System.Web.Mvc;
using Web.Components;
using SilenthinkContract;
using SilenthinkContract.Domain;
using SilenthinkCommon.Extension;
using SilenthinkCommon.ActionResults;
using SilenthinkContract.Component;

namespace Web.Areas.Cart.Controllers
{
    public class CartController : CartBaseController
    {
        public CartController(ILogService logService, IBaseService baseService, IExtraService extraService, IStoreService storeService, IOrderService orderService, IGameService gameService, IAuctionService auctionService, IPassportService passportService, IPaymentService paymentService, IMemcachedClient memcachedClient) : base(logService, baseService, extraService, storeService, orderService, gameService, auctionService, passportService, paymentService, memcachedClient)
        {
        }

        /// <summary>
        /// 查看购物车
        /// </summary>
        /// <returns></returns>
        public ActionResult Index(ShoppingCart cart, ShoppingCartOperate opt = ShoppingCartOperate.UpdateQuantity, Guid? id = null, int? qty = 0)
        {
            if (Request.IsAjaxRequest())
            {
                switch (opt)
                {
                    case ShoppingCartOperate.Remove:
                        if (id.HasValue)
                        {
                            cart.Remove(id.Value);
                        }
                        break;
                    case ShoppingCartOperate.Clear:
                        cart.Clear();
                        break;
                    default:
                        if (id.HasValue && qty.HasValue)
                        {
                            cart.UpdateQuantity(id.Value, qty.Value);
                        }
                        break;
                }
            }
            ProcessDiscount(cart);
            return PartialView(cart);
        }

        /// <summary>
        /// 添加到购物车
        /// </summary>
        /// <param name="param">商品Id </param>
        /// <param name="id">商品变体Id </param>
        /// <param name="qty">数量 </param>
        /// <param name="callback">CallBack</param>
        /// <param name="cart">ShoppingCart</param>
        /// <returns></returns>
        public ActionResult Add(long? param, Guid? id, string callback, ShoppingCart cart, int qty = 1)
        {
            var validate = new SkResult<string>();

            if (!param.HasValue || !id.HasValue || string.IsNullOrEmpty(callback))
            {
                validate.Message = "请检查参数";
                return Jsonp(validate, callback);
            }
            //var shoppingCartConfig = InfrastructureApi.GetSystemConfig().ShoppinCartConfig;
            var anonymousBuyEnabled = true; //shoppingCartConfig.AnonymousBuyEnabled;

            if (!anonymousBuyEnabled && !Request.IsAuthenticated)
            {
                validate.Message = "请先登录";
                return Jsonp(validate, callback);
            }
            if (Request.IsAuthenticated)
            {
                cart.Identity = User.Identity;
            }
            var result = new SkResult<MiniShoppingCart>();

            var product = StoreService.GetProduct(param.Value, false, true);
            if (product != null)
            {
                var variant = product.ProductVariants.FirstOrDefault(o => o.Id == id.Value);
                if (variant != null)
                {
                    var item = new ShoppingCartItem();
                    item.Id = param.Value;
                    item.VariantId = id.Value;
                    item.Name = product.Name;
                    item.UnitPrice = variant.VariantPrice;
                    item.Stock = variant.VariantQuantity;
                    item.OrderMaxQuantity = 4;
                    item.Quantity = qty;

                    cart.Add(id.Value, item);
                    result.Status = true;
                    result.Data = cart.ToMiniCart();
                    result.Message = string.Empty;
                }
            }
            ProcessDiscount(cart);
            return Jsonp(result, callback);
        }

        public ActionResult Remove(Guid? guid, string callback, ShoppingCart cart)
        {
            var result = new SkResult<ShoppingCart>();
            if (guid.HasValue)
            {
                cart.Remove(guid.Value);
            }
            return Jsonp(result, callback);
        }

        public ActionResult Clear(string callback)
        {
            Session[CartSessionKey] = null;
            var result = new SkResult<string>(true, string.Empty);
            return Jsonp(result, callback);
        }

        public ActionResult Mini(string callback, ShoppingCart cart)
        {
            var miniCart = cart.ToMiniCart();
            var result = new SkResult<MiniShoppingCart>(true, miniCart);
            return Jsonp(result, callback);
        }

        protected ActionResult Jsonp<T>(T data, string callback)
        {
            return new JsonpResult<T>(data, callback);
        }

        [HttpPost]
        public ActionResult Address(int param = 0)
        {
            var userId = User.Identity.SkIdentity().Id;
            UserAddress model = null;
            if (param > 0)
            {
                model = PassportService.GetUserAddress(param, userId);
            }
            return PartialView(model);
        }
    }
}
